package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

@Component
public class ManagerFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 请求前(pre)或请求后(post)执行
     * pre ：可以在请求被路由之前调用
     * route ：在路由请求时候被调用
     * post ：在route和error过滤器之后被调用
     * error ：处理请求时发生错误时被调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 优先级为0，数字越大，优先级越低
     * 通过int值来定义过滤器的执行顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0; // 优先级为0，数字越大，优先级越低
    }

    /**
     * 是否执行该过滤器，此处为true，说明需要过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器内执行的操作 return 任何 object 都标识继续执行
     * setsendzullResponse(false) 表示不再继续执行
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("zuul过滤器...");
        // 得到request上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 得到request域
        HttpServletRequest request = currentContext.getRequest();
        String url = request.getRequestURL().toString();
        if (url.indexOf("/admin/login")>0){
            System.out.println("登录页面"+url);
            return null;
        }
        //得到头信息
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer ")){
            String token = authorization.substring(7);
            Claims claims = null;
            try {
                claims = jwtUtil.parseJWT(token);
                if (claims!=null){
                    if ("admin".equals(claims.get("roles")));{
                        currentContext.addZuulRequestHeader("Authorization", authorization);
                        System.out.println("token 验证通过，添加了头信息"+authorization);
                        return null;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //终止运行
        currentContext.setSendZuulResponse(false);
        //http状态码
        currentContext.setResponseStatusCode(403);
        currentContext.setResponseBody("权限不足");
        currentContext.getResponse().setContentType("text/html;charset=UTF-8");
        return null;
    }
}
